#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time    : 2024/10/18 上午10:58
@Author  : Sugar
@File    : log.py
@Desc    :
"""
import os
import logging
import colorlog
from logging.handlers import TimedRotatingFileHandler


# 定义不同日志等级颜色
log_colors_config = {
    "DEBUG": "bold_cyan",
    "INFO": "bold_green",
    "WARNING": "bold_yellow",
    "ERROR": "bold_red",
    "CRITICAL": "red",
}
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
os.makedirs(log_dir, exist_ok=True)

log_file = os.path.join(log_dir, "app.log")


class LoggerHandler(logging.Logger):
    def __init__(
        self,
        name="root",
        level="DEBUG",
        file=log_file,
        encoding="utf-8",
        save_log=True,
        out_log=True,
    ):
        super().__init__(name)
        self.encoding = encoding
        self.file = file
        self.level = level
        # 针对所需要的日志信息 手动调整颜色
        formatter = colorlog.ColoredFormatter(
            "%(log_color)s%(levelname)s %(asctime)s %(reset)s| %(message_log_color)s%(levelname)-8s %(reset)s| %("
            "log_color)s[%(filename)s%(reset)s:%(log_color)s%(module)s%(reset)s:%(log_color)s%(funcName)s%("
            "reset)s:%(log_color)s%("
            "lineno)d] %(reset)s- %(log_color)s%(message)s",
            reset=True,
            log_colors=log_colors_config,
            secondary_log_colors={
                "message": {
                    "DEBUG": "blue",
                    "INFO": "blue",
                    "WARNING": "blue",
                    "ERROR": "red",
                    "CRITICAL": "bold_red",
                }
            },
            style="%",
        )  # 日志输出格式

        # 创建一个FileHandler，用于写到本地
        if save_log:
            rotatingFileHandler = TimedRotatingFileHandler(
                filename=self.file,
                when="D",
                backupCount=7,
                encoding="utf-8",
            )
            format = "%(asctime)s|%(filename)s[lines:%(lineno)d]|[function:%(funcName)s]|%(levelname)s: %(message)s"
            rotatingFileHandler.setFormatter(
                logging.Formatter(format, datefmt="%Y-%m-%d %H:%M:%S")
            )
            rotatingFileHandler.setLevel(logging.DEBUG)
            self.addHandler(rotatingFileHandler)

        # 创建一个StreamHandler,用于输出到控制台
        if out_log:
            console = colorlog.StreamHandler()
            console.setLevel(logging.DEBUG)
            console.setFormatter(formatter)
            self.addHandler(console)
            self.setLevel(logging.DEBUG)

log = LoggerHandler()
